package com.woniu.bh.backstage.feign;

import feign.Client;
import feign.Logger.Level;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @version: V1.0
 * @author: 陈小宝
 * @className: FeignConfig
 * @packageName: com.woniu.feign
 * @description:
 * @data: 2020-09-18 16:39
 */
@Component
public class FeignConfig implements  RequestInterceptor{

    //配置日志
    @Bean
    public Level createLevel(){
        return Level.FULL;
    }

    /**
     * feign请求拦截器
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求Spring信息
        ServletRequestAttributes attributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        // 获取请求体
        HttpServletRequest request = attributes.getRequest();
        // 获取Header、或参数等
        String token = request.getHeader("X-Token");
        System.out.println("拦截器拦截的token"+token);
        // 注入Feign请求体
        requestTemplate.header("X-Token",token);
    }

//    @Bean
//    public CertificatesVerify certificatesVerify(){
//        return  new CertificatesVerify();
//    }
//
//    @Bean
//    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
//        return new RestTemplate(factory);
//    }
//
//    @Bean
//    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
//        SSL factory = new SSL();
//        factory.setReadTimeout(5000);
//        factory.setConnectTimeout(15000);
//        return factory;
//    }

//    @Bean
//    @ConditionalOnMissingBean
//    public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
//                              SpringClientFactory clientFactory) throws NoSuchAlgorithmException, KeyManagementException {
//        SSLContext ctx = SSLContext.getInstance("SSL");
//        X509TrustManager tm = new X509TrustManager() {
//            @Override
//            public void checkClientTrusted(X509Certificate[] chain,
//                                           String authType) throws CertificateException {
//            }
//
//            @Override
//            public void checkServerTrusted(X509Certificate[] chain,
//                                           String authType) throws CertificateException {
//            }
//
//            @Override
//            public X509Certificate[] getAcceptedIssuers() {
//                return null;
//            }
//        };
//        ctx.init(null, new TrustManager[]{tm}, null);
//        return new LoadBalancerFeignClient(new Client.Default(ctx.getSocketFactory(),
//                new HostnameVerifier() {
//
//                    @Override
//                    public boolean verify(String hostname, SSLSession session) {
//                        // TODO Auto-generated method stub
//                        return true;
//                    }
//                }),
//                cachingFactory, clientFactory);
//    }

//    //增加SSL
//    public static SSLSocketFactory getSSLSocketFactory() {
//        //TODO Exception 需要抛出异常
//        SSLContext sslContext = null;
//        BASE64Decoder decoder = new BASE64Decoder();
//        InputStream keyStoreInput = null;
//        InputStream trustStoreInput = null;
//        String keyStoreBaseStr = keyStore;
//        String userIdBaseStr = trustStore;
//        try {
//            byte[] keyStoreBytes = decoder.decodeBuffer(keyStoreBaseStr);
//            byte[] trustStoreBytes = decoder.decodeBuffer(userIdBaseStr);
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keyStoreInput = new ByteArrayInputStream(keyStoreBytes);
//            keyStore.load(keyStoreInput, password.toCharArray());
//
//            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            trustStoreInput = new ByteArrayInputStream(trustStoreBytes);
//            trustStore.load(trustStoreInput, null);
//            sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray())
//                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//        } catch (KeyStoreException e) {
//            e.printStackTrace();
//        } catch (CertificateException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (UnrecoverableKeyException e) {
//            e.printStackTrace();
//        }
//        return sslContext.getSocketFactory();
//    }


//    @Bean
//    @LoadBalanced
//    public RestTemplate restTemplate() {
//        //复杂构造函数的使用
//        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//        requestFactory.setConnectTimeout(30000);// 设置超时
//        requestFactory.setReadTimeout(30000);
//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.setRequestFactory(requestFactory);
//        restTemplate.setInterceptors(Arrays.asList(new RestTemplateInterceptor()));
//        return restTemplate;
//    }

//    @Bean
//    @ConditionalOnMissingBean
//    public Client feignClient(CachingSpringLoadBalancerFactory cachingSpringLoadBalancerFactory,
//                              SpringClientFactory clientFactory) throws NoSuchAlgorithmException, KeyManagementException {
//        SSLContext ctx = SSLContext.getInstance("SSL");
//        X509TrustManager tm = new X509TrustManager() {
//            @Override
//            public void checkClientTrusted(X509Certificate[] chain,
//                                           String authType) throws CertificateException {
//            }
//
//            @Override
//            public void checkServerTrusted(X509Certificate[] chain,
//                                           String authType) throws CertificateException {
//            }
//
//            @Override
//            public X509Certificate[] getAcceptedIssuers() {
//                return null;
//            }
//        };
//        ctx.init(null, new TrustManager[]{tm}, null);
//        return new LoadBalancerFeignClient(new Client.Default(ctx.getSocketFactory(),
//                new HostnameVerifier() {
//
//                    @Override
//                    public boolean verify(String hostname, SSLSession session) {
//                        // TODO Auto-generated method stub
//                        return true;
//                    }
//                }),
//                cachingSpringLoadBalancerFactory, clientFactory);
//    }


}
